package com.zyh.scs.admin.filter;

import cn.hutool.core.util.StrUtil;
import com.zyh.scs.common.core.util.MinioUtil;
import io.minio.GetObjectResponse;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class FileFilter implements Filter {
    @Autowired
    private MinioUtil minioUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init FileFilter");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        // 检查请求路径是否需要转发
        if (requestURI.startsWith("/admin/file")) {
            // 构造目标 URL 去掉 "/forward"
            log.info("requestURI: {}", requestURI);
            // rls/aaa/bbb.png
            String path = requestURI.substring(12);
            String bucketName = path.substring(0, path.indexOf("/"));
            String fileUrl = path.substring(path.indexOf("/"));
            String filename = null;
            String filenameSuffix = path.substring(path.lastIndexOf("."));
            String filenameParam = httpRequest.getParameter("filename");
            if (filenameParam != null && !filenameParam.isEmpty()) {
                filename = filenameParam + filenameSuffix;
            }
            try (GetObjectResponse objResponse = minioUtil.getObject(bucketName, fileUrl)) {
                // 设置响应头，告诉浏览器这是一个文件下载
                if (StrUtil.isNotBlank(filename)){
                    String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
                    httpResponse.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"; filename*=UTF-8''" + encodedFilename);
                }
                httpResponse.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                httpResponse.setStatus(HttpServletResponse.SC_OK);
                // 使用 Hutool 的 StreamUtil 直接写入输出流

                try (OutputStream out = response.getOutputStream()) {
                    IOUtils.copy(objResponse, out);
                    out.flush();
                }
            }catch (Exception e){
                if (minioUtil.getBucketName().equals(bucketName)) {
                    httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
                }else {
                    httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }
            }
            return;
        }
        chain.doFilter(httpRequest, response);
    }

    @Override
    public void destroy() {
        log.info("destroy FileFilter");
    }
}